package main

import (
	"bufio"
	"encoding/json"
	"net"
	"net/http"
)

func main() {
	Dial()
	hdl := new(server)
	http.ListenAndServe(":23086", hdl)
}

type server struct{}

func (s server) ServeHTTP(res http.ResponseWriter, request *http.Request) {
	bd := request.Body
	println(request.ContentLength)
	defer bd.Close()
	var body = make([]byte, request.ContentLength)
	//_, e := bd.Read(body)
	bf := bufio.NewReader(bd)
	_, e := bf.Read(body)
	if e != nil {
		println("read error = " + e.Error())
	}

	println(string(body))
	p := new(Param)
	err := json.Unmarshal(body, &p)
	if err != nil {
		println(string(body))
		println(err.Error())
	} else {
		Print(p.Printer, p.Url)
	}

	res.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	res.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	//res.Header().Set("content-type", "application/json")             //返回数据格式是json

}

type Param struct {
	Url     string `json:"url"`
	Printer string `json:"printer"`
}

var conn net.Conn
var err error

func Dial() {
	conn, err = net.Dial("tcp", "127.0.0.1:23085")
	if err != nil {
		println(err.Error())
	}
}

//{
//dev:"",//打印机名称
//url:"",//需要打印的网址
//w:0,//纸张宽度
//h:0,//纸张高度
//p:0,//页边距padding
//type:0,//0是小票打印机，1是条码打印机，
//}
type cmd struct {
	Dev  string `json:"dev"`
	Url  string `json:"url"`
	W    int    `json:"w"`
	H    int    `json:"h"`
	P    int    `json:"p"`
	Type int    `json:"type"`
}

func (c *cmd) ToString() []byte {
	data, err := json.Marshal(c)
	if err != nil {
		return nil
	}
	return data
}

func Print(printer string, url string) {
	c := new(cmd)
	c.Type = 1
	c.Url = url
	c.P = 0
	c.W = 60
	c.H = 40
	c.Dev = printer
	conn.Write(c.ToString())
}
